package com.wugh.fast.kernel.util;

import com.wugh.fast.kernel.core.props.FastProperties;
import com.wugh.fast.kernel.core.util.SpringContextHolder;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

/**
 * @author 吴冠辉
 * @date 2018/1/18
 */
public class EncryptUtils {
    /**
     * 默认点的SHA加密的SALT
     */

    public final static String DEFAULT_SECURE_HASH_ALGORITHM_SALT;
    public final static String DEFAULT_ENCODING = "UTF-8";

    static {
        FastProperties fastProperties = null;
        try {
            fastProperties = SpringContextHolder.getBean(FastProperties.class);
        } catch (Exception e) {
        }
        if (fastProperties != null && fastProperties.getEncrypt() != null && fastProperties.getEncrypt().getShaSalt() != null) {
            DEFAULT_SECURE_HASH_ALGORITHM_SALT = fastProperties.getEncrypt().getShaSalt();
        } else {
            DEFAULT_SECURE_HASH_ALGORITHM_SALT = "";
        }
    }

    private EncryptUtils() {
    }

    public static String encryptMD5(String data) {
        byte[] bytes = DigestUtils.md5(data);
        return Hex.encodeHexString(bytes);
    }

    /**
     * sha256加密
     * 使用默认的hashkey
     *
     * @param str 加密的字符串
     * @return
     */
    public static String encryptBySha256(String str) {
        return encryptBySha256(str, EncryptUtils.DEFAULT_SECURE_HASH_ALGORITHM_SALT);
    }

    /**
     * sha256加密
     *
     * @param str  需要加密的字符串
     * @param salt 加密用的key
     * @return
     */
    public static String encryptBySha256(String str, String salt) {
        try {
            MessageDigest sha256Digest = DigestUtils.getSha256Digest();
            sha256Digest.update(salt.getBytes(DEFAULT_ENCODING));
            byte[] digest = sha256Digest.digest(str.getBytes(DEFAULT_ENCODING));
            return Hex.encodeHexString(digest);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
